package field_REGEX_Definitions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import fields.AbstractField;

public class CustomField implements Field{
	public String name;
	public String type;
	public String[] alias;
	
	public CustomField(String fName,String tp,String[] aNames){
		name = fName;
		type = tp;
		alias = sortByLength(aNames);
		
	}
	
	public String getFieldName(){
		return name;
	}
	
	@Override
	public boolean matches(String input) {
		Pattern pattern;
		Matcher matcher;
		for(String aName : alias){
			pattern = Pattern.compile(toRegex(aName),Pattern.CASE_INSENSITIVE);
			matcher = pattern.matcher(input);
			if(matcher.find()){
				return true;
			}
		}
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public AbstractField execute() {
		// TODO Auto-generated method stub
		return null;
	}
	
	private String toRegex(String s){
		
		return "(.*)("+s.replaceAll("\\s+","\\s*")+")(.*)";
	}
	
	/**
	 * Sorts list of aliases from longest to shortest so that matching will occur in that order.
	 * @param s
	 * @return
	 */
	private String[] sortByLength(String[] s){
		String[] temp = new String[s.length];
		String word;
		int index1=0,index2=0;
		for(String s1 : s){
			word = s1;
			for(String s2 : s){
				if(s2.length()>s1.length() && index2>index1){
					word = s2;
					index2++;
				}
			}
			temp[index1] = word;
			index1++;
		}
		return temp.clone();
	}
	
	public String toXML(){
		String xmlString = "\t<FIELD name = "+"\""+name+"\" type = "+"\""+type+"\" alias = ";
		int index=0;
		for(String s : alias){
			if(index<(alias.length-1))
				xmlString += "\""+s+"\""+",";
			else
				xmlString += "\""+s+"\""+">";			
		}
		xmlString += "</FIELD>\n";
		return xmlString;
	}

	@Override
	public String getFieldType() {
		return type;
	}

}
